import mongoose from 'mongoose';

import { connectMongoDB } from './database/mongodb';
import { Exam } from './models/exam.model';
import { Paper } from './models/paper.model';
import { Question } from './models/question.model';
import { User } from './models/user.model';

/**
 * 种子数据生成脚本
 * 
 * 功能说明：
 * 1. 清空现有数据库
 * 2. 创建测试用户（包含软删除字段支持）
 * 3. 创建示例试题、试卷和考试活动
 * 
 * 软删除功能：
 * - 所有用户创建时默认设置 is_deleted: false
 * - deleted_at 字段初始为 null
 * - 支持通过管理界面进行软删除操作
 */

const seedData = async () => {
  try {
    // 连接数据库
    await connectMongoDB();
    
    console.log('开始清理数据库...');
    
    // 删除整个数据库重新开始
    await mongoose.connection.db!.dropDatabase();
    console.log('数据库已清理');
    
    console.log('开始创建种子数据...');
    
    // 创建管理员用户
    const adminUser = new User({
      username: 'admin',
      password: '123456',
      phone: '18888888888',
      role: 'admin',
      status: 'active',
      is_deleted: false,
      deleted_at: null
    });
    
    const savedAdmin = await adminUser.save();
    console.log('管理员用户创建成功:', savedAdmin.username);
    
    // 创建普通用户
    const normalUser = new User({
      username: 'user1',
      password: '123456',
      phone: '18999999999',
      role: 'user',
      status: 'active',
      is_deleted: false,
      deleted_at: null
    });
    
    const savedUser = await normalUser.save();
    console.log('普通用户创建成功:', savedUser.username);
    
    
    // 创建示例试题
    const questions = [
      {
        content: '以下哪个是JavaScript的数据类型？',
        type: 'Select',
        options: [
          { symbol: 'A', content: 'string' },
          { symbol: 'B', content: 'number' },
          { symbol: 'C', content: 'boolean' },
          { symbol: 'D', content: '以上都是' }
        ],
        answer: [3], // D选项
        score: 2,
        difficulty: '简单',
        creator: savedAdmin._id
      },
      {
        content: 'React是一个用于构建用户界面的JavaScript库',
        type: 'Judgement',
        options: [
          { symbol: 'A', content: '正确' },
          { symbol: 'B', content: '错误' }
        ],
        answer: [0], // 正确
        score: 1,
        difficulty: '简单',
        creator: savedAdmin._id
      },
      {
        content: '以下哪些是Vue.js的特性？（多选）',
        type: 'multiSelect',
        options: [
          { symbol: 'A', content: '响应式数据绑定' },
          { symbol: 'B', content: '组件化开发' },
          { symbol: 'C', content: '虚拟DOM' },
          { symbol: 'D', content: '静态类型检查' }
        ],
        answer: [0, 1, 2], // A、B、C选项
        score: 3,
        difficulty: '中等',
        creator: savedAdmin._id
      },
      {
        content: '什么是React Hook？',
        type: 'Select',
        options: [
          { symbol: 'A', content: '生命周期函数' },
          { symbol: 'B', content: 'Hook函数' },
          { symbol: 'C', content: '组件' },
          { symbol: 'D', content: '事件处理器' }
        ],
        answer: [1], // B选项
        score: 2,
        difficulty: '中等',
        creator: savedAdmin._id
      },
      {
        content: 'Node.js可以运行在浏览器中',
        type: 'Judgement',
        options: [
          { symbol: 'A', content: '正确' },
          { symbol: 'B', content: '错误' }
        ],
        answer: [1], // 错误
        score: 1,
        difficulty: '简单',
        creator: savedAdmin._id
      },
      {
        content: '以下哪些是前端框架？（多选）',
        type: 'multiSelect',
        options: [
          { symbol: 'A', content: 'React' },
          { symbol: 'B', content: 'Vue' },
          { symbol: 'C', content: 'Angular' },
          { symbol: 'D', content: 'Express' }
        ],
        answer: [0, 1, 2], // A、B、C选项
        score: 3,
        difficulty: '简单',
        creator: savedAdmin._id
      }
    ];
    
    const savedQuestions = [];
    for (const questionData of questions) {
      const question = new Question(questionData);
      const savedQuestion = await question.save();
      savedQuestions.push(savedQuestion);
      console.log('试题创建成功:', savedQuestion.content.substring(0, 20) + '...');
    }
    
    // 创建试卷
    const papers = [
      {
        paper_name: 'JavaScript基础测试',
        description: '测试JavaScript基础知识',
        question_list: [savedQuestions[0]._id, savedQuestions[1]._id, savedQuestions[3]._id],
        duration: 60,
        total_score: 5,
        status: 'published',
        creator: savedAdmin._id
      },
      {
        paper_name: '前端框架综合测试',
        description: '测试React、Vue等前端框架相关知识',
        question_list: [savedQuestions[2]._id, savedQuestions[4]._id, savedQuestions[5]._id],
        duration: 90,
        total_score: 7,
        status: 'published',
        creator: savedAdmin._id
      },
      {
        paper_name: '前端开发能力测试（草稿）',
        description: '全面测试前端开发能力',
        question_list: savedQuestions.map(q => q._id),
        duration: 120,
        total_score: 12,
        status: 'draft',
        creator: savedAdmin._id
      }
    ];
    
    const savedPapers = [];
    for (const paperData of papers) {
      const paper = new Paper(paperData);
      const savedPaper = await paper.save();
      savedPapers.push(savedPaper);
      console.log('试卷创建成功:', savedPaper.paper_name);
    }
    
    // 创建考试活动
    const now = new Date();
    const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000);
    const nextWeek = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
    
    const exams = [
      {
        exam_name: 'JavaScript基础考试',
        description: '检验JavaScript基础知识掌握情况',
        start_time: now,
        end_time: tomorrow,
        paper: savedPapers[0]._id,
        is_enabled: true,
        participation_limit: 50,
        allow_retake: false,
        creator: savedAdmin._id
      },
      {
        exam_name: '前端框架能力测试',
        description: '测试前端框架的理解和应用能力',
        start_time: tomorrow,
        end_time: nextWeek,
        paper: savedPapers[1]._id,
        is_enabled: true,
        participation_limit: 0,
        allow_retake: true,
        creator: savedAdmin._id
      },
      {
        exam_name: '前端开发综合评估（未启用）',
        description: '全面评估前端开发能力',
        start_time: nextWeek,
        end_time: new Date(nextWeek.getTime() + 7 * 24 * 60 * 60 * 1000),
        paper: savedPapers[2]._id,
        is_enabled: false,
        participation_limit: 30,
        allow_retake: false,
        creator: savedAdmin._id
      }
    ];
    
    for (const examData of exams) {
      const exam = new Exam(examData);
     
      const savedExam = await exam.save();
      console.log('考试活动创建成功:', savedExam.exam_name);
    }
    
    console.log('\n========== 种子数据创建完成！ ==========');
    console.log('管理员账号 - 用户名: admin, 密码: 123456, 手机号: 18888888888');
    console.log('普通用户账号 - 用户名: user1, 密码: 123456, 手机号: 18999999999');
    console.log(`创建了 ${savedQuestions.length} 道试题`);
    console.log(`创建了 ${savedPapers.length} 张试卷`);
    console.log(`创建了 ${exams.length} 个考试活动`);
    console.log('所有用户均设置为未删除状态（is_deleted: false）');
    console.log('=======================================\n');
    
    process.exit(0);
    
  } catch (error) {
    console.error('创建种子数据失败:', error);
    process.exit(1);
  }
};

seedData();
